//
//  UIDataRecorder.m
//  UI_Test_Frame
//
//  Created by tdh1 on 01/09/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "UIDataRecorder.h"
#import "UIOrientationBlackBox.h"
#import "UI_Test_FrameAppDelegate.h"
#import <QuartzCore/QuartzCore.h>
#import <CoreGraphics/CoreGraphics.h>

#pragma mark UIDataLogItem

@implementation UIDataLogItem
@synthesize touchType, timeOfEvent, name, event, touches, x, y, z, latitude, longitude, altitude, touchX, touchY;

- (id) init
{
	self = [super init];
	if (self != nil) {
		touches = nil;
		event = nil;
		name = nil;
	}
	return self;
}

- (NSString*)description
{
	NSMutableString * rtrnString = [NSMutableString stringWithCapacity:200];
	
	if (name == nil){
		switch (self.touchType) {
			case touchTypeBegan:
				[rtrnString appendFormat: @"B-"];
				break;
			case touchTypeEnded:
				[rtrnString appendFormat: @"E-"];
				break;
			case touchTypeMoved:
				[rtrnString appendFormat: @"M-"];
				break;
			case touchTypeCancelled:
				[rtrnString appendFormat: @"C-"];
				break;
			default:
				break;
		}
	} else {
		[rtrnString appendFormat: @"%@-",self.name];
	}
		
	NSDate *date = [NSDate dateWithTimeIntervalSince1970:self.timeOfEvent];
	NSString *dateStr = [date description];
	//const char *dateStrPtr = [dateStr UTF8String];
	
	// format: YYYY-MM-DD HH:MM:SS ±HHMM
//	int year, month, day, hour, minutes, seconds;
//	sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minutes, &seconds);
//	year -= 1970;
		
	[rtrnString appendFormat: @"%@ t:%f:t ",dateStr, [date timeIntervalSinceReferenceDate]];
	
	//NSLog([[NSDate dateWithTimeIntervalSinceReferenceDate: [date timeIntervalSinceReferenceDate]] description]); 
	
	[rtrnString appendFormat: @"lt:%f ln:%f ",self.latitude, self.longitude];
	[rtrnString appendFormat: @"xo:%f:xo yo:%f:yo zo:%f:zo ",self.x, self.y, self.z];
	
/*	for (UITouch *myTouch in self.touches){
		[rtrnString appendFormat: @"%f, %f", [myTouch locationInView: [(UI_Test_FrameAppDelegate*) [[UIApplication sharedApplication] delegate] window]].x, [myTouch locationInView: [(UI_Test_FrameAppDelegate*) [[UIApplication sharedApplication] delegate] window]].y];
	}*/
	
	[rtrnString appendFormat: @"x:%f:x, y:%f:y", self.touchX, self.touchY];
	
	return rtrnString;
}

- (void) dealloc
{
	if(touches != nil){
		[touches release];
	}
	
	if(event != nil){
		[event release];
	}
	
	[super dealloc];
}


@end

#pragma mark -
#pragma mark UIDataRecorder

@implementation UIDataRecorder

@synthesize mainWindow;

static UIDataRecorder *sharedDataRecorder = nil;

+ (UIDataRecorder*)sharedDataRecorder
{
	if (sharedDataRecorder == nil){
		sharedDataRecorder = [[UIDataRecorder alloc] init];
	}
	
	return sharedDataRecorder;
}

- (id) init
{
	self = [super init];
	if (self != nil) {
		
		srandom([[NSDate date] timeIntervalSince1970]);
		myUuid = [[NSString stringWithFormat: @"%f",[[NSDate date] timeIntervalSince1970]] retain];
		[[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithFormat:@"%@/%@",[self applicationDocumentsDirectory],myUuid] withIntermediateDirectories:NO attributes:nil error:nil];
		
		eventLog = [[NSMutableArray alloc] init];
		conditionNme = NULL;
	}
	return self;
}

// Must be done after an event is started but prior to closing.
- (void)beginCondition:(NSString *)conditionName
{
	if (conditionNme != NULL)[conditionNme release];
	conditionNme = conditionName;
	[conditionNme retain];
}

- (void)addEvent:(TouchType)touchType andTouches:(NSSet*)touches andEvent:(UIEvent*)event
{
	UIDataLogItem *newItem = [[UIDataLogItem alloc] init];

	newItem.touchType = touchType;
	newItem.timeOfEvent = [[NSDate date] timeIntervalSince1970];
	
	newItem.touches = touches;
	
	newItem.touchX = [[touches anyObject] locationInView: [(UI_Test_FrameAppDelegate*) [[UIApplication sharedApplication] delegate] window]].x;
	newItem.touchY = [[touches anyObject] locationInView: [(UI_Test_FrameAppDelegate*) [[UIApplication sharedApplication] delegate] window]].y;
	
	newItem.x = [[UIOrientationBlackBox sharedBlackBox] x];
	newItem.y = [[UIOrientationBlackBox sharedBlackBox] y];
	newItem.z = [[UIOrientationBlackBox sharedBlackBox] z];
	
	newItem.longitude = [[UIOrientationBlackBox sharedBlackBox] longitude];
	newItem.latitude = [[UIOrientationBlackBox sharedBlackBox] latitude];
	
	[eventLog addObject: newItem];
	[newItem release];
}

- (void)closeEventEpoch
{
	NSMutableString *toWrite = [[[NSMutableString alloc] init] autorelease];
	
	//NSDate *startdate = [NSDate dateWithTimeIntervalSince1970: [[eventLog objectAtIndex:0] timeOfEvent]];
	//NSDate *endDate = [NSDate dateWithTimeIntervalSince1970: [[eventLog lastObject] timeOfEvent]];
	
	for (UIDataLogItem *myItem in eventLog){		
			[toWrite appendFormat:@"%@\n",[myItem description]];
	}
	NSString * myPath;
	
	if (conditionNme == NULL){
		myPath = [NSString stringWithFormat:@"%@/%@/%d.txt",[self applicationDocumentsDirectory], myUuid, [[NSDate date] timeIntervalSince1970]];
	} else {
		myPath = [NSString stringWithFormat:@"%@/%@/%@.txt",[self applicationDocumentsDirectory], myUuid, conditionNme];
	}
	
	[toWrite writeToFile:myPath atomically:YES encoding: NSUTF8StringEncoding error:nil];
	
	[eventLog removeAllObjects];
	
	if (conditionNme != NULL){
		[conditionNme release];
		conditionNme = NULL;
	}
}

- (void)addCustomEvenType:(NSString *)specialEventName withTouches:(NSSet*)touches andEvent:(UIEvent*)event
{
	UIDataLogItem *newItem = [[UIDataLogItem alloc] init];
	
	//NSLog(@"%f, %f",[[touches anyObject] locationInView: [(UI_Test_FrameAppDelegate*) [[UIApplication sharedApplication] delegate] window]].x, [[touches anyObject] locationInView: [(UI_Test_FrameAppDelegate*) [[UIApplication sharedApplication] delegate] window]].y);
	
	//newItem.touchType = touchType;
	newItem.name = specialEventName;
	newItem.timeOfEvent = [[NSDate date] timeIntervalSince1970];
	
	newItem.touches = touches;
	
	newItem.touchX = [[touches anyObject] locationInView: [(UI_Test_FrameAppDelegate*) [[UIApplication sharedApplication] delegate] window]].x;
	newItem.touchY = [[touches anyObject] locationInView: [(UI_Test_FrameAppDelegate*) [[UIApplication sharedApplication] delegate] window]].y;
	
	newItem.x = [[UIOrientationBlackBox sharedBlackBox] x];
	newItem.y = [[UIOrientationBlackBox sharedBlackBox] y];
	newItem.z = [[UIOrientationBlackBox sharedBlackBox] z];
	
	newItem.longitude = [[UIOrientationBlackBox sharedBlackBox] longitude];
	newItem.latitude = [[UIOrientationBlackBox sharedBlackBox] latitude];
	
	[eventLog addObject: newItem];
	[newItem release];
}

- (void)captureScreenShot
{
	UIGraphicsBeginImageContext(mainWindow.frame.size);
	[mainWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
	UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(viewImage)];
	
	if (conditionNme == NULL){
		[imageData writeToFile:[NSString stringWithFormat:@"%@/%@/%f.png",[self applicationDocumentsDirectory], myUuid, [[NSDate date] timeIntervalSince1970]] atomically:YES];
	} else {
		[imageData writeToFile:[NSString stringWithFormat:@"%@/%@/%@__%f.png",[self applicationDocumentsDirectory], myUuid, conditionNme,[[NSDate date] timeIntervalSince1970]] atomically:YES];
	}
	
	
}

//Returns the path to the application's documents directory. 
- (NSString *)applicationDocumentsDirectory
{	
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    return basePath;
}

@end
